package top.lhj.security.example.config;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author LiDeJie
 * @Create 2024/2/4 20:06
 * @Version 1.0
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    
        //用户的证人信息
        Object principal = authentication.getPrincipal(); 
        //用户的凭证信息
        Object credentials = authentication.getCredentials();   
        //用户的全新
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        //封装相应结果
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "认证成功");
        result.put("data", principal);
        String json = JSONObject.toJSONString(result);
        
        //设置相应状态码
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}
